import {
	createRouter,
	createWebHashHistory
} from 'vue-router'

import {
	isTokenExpired,
	refreshToken
} from "@/components/auth";

const routes = [{
		path: '/login',
		name: 'login',
		component: () => import('../views/LoginView.vue')
	},
	{
		path: '/register',
		name: 'register',
		component: () => import('../views/RegisterView.vue')
	},
	{
		path: '/test1',
		name: 'test1',
		component: () => import('../views/Test1View.vue')
	},
	{
		path: "/test2",
		name: "test2",
		component: () => import("../views/LayoutView.vue")
	},
	{
		path: '/',
		component: () => import('../views/LayoutView.vue'),
		children: [{
				path: '',
				name: 'home',
				component: () => import('../views/ChatView.vue'),
				children: [{
					path: '/chat/:id',
					name: 'chat',
					component: () => import('../views/Chat.vue'),
					props: true
				}]
			},
			{
				path: 'profile',
				name: 'profile',
				component: () => import('../views/ProfileView.vue')
			},
			{
				path: 'settings',
				name: 'settings',
				component: () => import('../views/SettingsView.vue')
			},
			{
				path: 'contacts',
				name: 'contacts',
				component: () => import('../views/ContactsView.vue')
			}
		]
	},
]


const router = createRouter({
	history: createWebHashHistory(),
	routes
})

router.beforeEach(async (to, from, next) => {
	const accessToken = localStorage.getItem('Token');
	if (isTokenExpired(accessToken) && to.name !== 'login' && to.name !== 'register') {
		next({
			name: 'login'
		});
	} else {
		next();
	}
})

export default router